<!--
  * 角色 岗位 列表
-->
<template>
  <div>
    <div class="header">
      <div>
        关键字：
        <a-input style="width: 250px" v-model:value="queryForm.name" placeholder="岗位名称" />
        是否有效：
        <a-switch v-model:checked="queryForm.state" checked-children="是" checkedValue="Y"  un-checked-children="否" unCheckedValue="N" />

        <a-button class="button-style" v-if="selectDataScopeId" type="primary" @click="queryRoleEmployee">搜索</a-button>
        <a-button class="button-style" v-if="selectDataScopeId" type="default" @click="resetQueryRoleEmployee">重置</a-button>
      </div>

      <div>
        <a-button class="button-style" v-if="selectDataScopeId" type="primary" @click="addRoleQuarter" v-privilege="'system:ds:quarter:add'"
          >添加岗位</a-button
        >
        <a-button class="button-style" v-if="selectDataScopeId" type="primary" danger @click="batchDelete" v-privilege="'system:ds:quarter:batch:delete'"
          >批量移除</a-button
        >
      </div>
    </div>
    <a-table
      :loading="tableLoading"
      :dataSource="tableData"
      :columns="columns"
      :pagination="false"
      :scroll="{ y: 400 }"
      rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      size="small"
      bordered
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'state'">
          <span>{{ $smartEnumPlugin.getDescByValue('FLAG_ENUM', text) }}</span>
        </template>
        <template v-if="column.dataIndex === 'operate'">
          <a @click="deleteEmployeeRole(record.id)" v-privilege="'system:ds:quarter:delete'">移除</a>
        </template>
      </template>
    </a-table>
    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageIndex"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryRoleEmployee"
        @showSizeChange="queryRoleEmployee"
        :show-total="showTableTotal"
      />
    </div>
    <QuarterTabSelect ref="selectQuarterModal" @selectData="selectData" />
  </div>
</template>
<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue';
  import _ from 'lodash';
  import { computed, inject, onMounted, reactive, ref, watch } from 'vue';
  import { dsApi } from '/@/api/system/auth/ds-api'
  import { PAGE_SIZE, showTableTotal, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import QuarterTabSelect from './quarter-tab-select-modal.vue';
  import { smartSentry } from '/@/lib/smart-sentry';

  // ----------------------- 以下是字段定义 emits props ---------------------
  let selectDataScopeId = inject('selectDataScopeId');

  // ----------------------- 员工列表：显示和搜索 ------------------------
  watch(
    () => selectDataScopeId.value,
    () => queryRoleEmployee()
  );

  onMounted(queryRoleEmployee);

  const defaultQueryForm = {
    pageIndex: 1,
    pageSize: PAGE_SIZE,
    dsId: undefined,
    name: undefined,
    state: "Y",
    isRelate: true,
  };
  // 查询表单
  const queryForm = reactive({ ...defaultQueryForm });
  // 总数
  const total = ref(0);
  // 表格数据
  const tableData = ref([]);
  // 表格loading效果
  const tableLoading = ref(false);

  function resetQueryRoleEmployee() {
    queryForm.name = '';
    queryRoleEmployee();
  }

  async function queryRoleEmployee() {
    try {
      tableLoading.value = true;
      queryForm.dsId = selectDataScopeId.value;
      let res = await dsApi.queryRoleQuarter(queryForm);
      tableData.value = res.data.data;
      total.value = res.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  const columns = reactive([
    {
      title: '岗位名称',
      dataIndex: 'name',
    },
    {
      title: '是否有效',
      dataIndex: 'state',
    },
    {
      title: '排序号',
      dataIndex: 'showOrder',
    },
    {
      title: '描述',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      dataIndex: 'operate',
      width: 60,
    },
  ]);

  // ----------------------- 添加成员 ---------------------------------
  const selectQuarterModal = ref();

  async function addRoleQuarter() {
    selectQuarterModal.value.showModal(selectDataScopeId.value);
  }

  async function selectData(list) {
    if (_.isEmpty(list)) {
      message.warning('请选择角色人员');
      return;
    }
    SmartLoading.show();
    try {
      let params = {
        authList: list,
        dsId: selectDataScopeId.value,
        isRelate: true,
      };
      let res=await dsApi.relateOrCancelQuarterAuth(params);
      if(res.success){
        message.success(res.message);
        await queryRoleEmployee();
      }
      else
        message.error(res.message);
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ----------------------- 移除成员 ---------------------------------
  // 删除角色成员方法
  async function deleteEmployeeRole(employeeId) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该角色成员么？',
      okText: '确定',
      okType: 'danger',
      async onOk() {
        SmartLoading.show();
        try {
          let params = {
            authList: [employeeId],
            dsId: selectDataScopeId.value,
            isRelate: false,
          };
          let res=await dsApi.relateOrCancelQuarterAuth(params);
          if(res.success){
            message.success(res.message);
            await queryRoleEmployee();
          }
          else
            message.error(res.message);
        } catch (e) {
          smartSentry.captureError(e);
        } finally {
          SmartLoading.hide();
        }
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  // ----------------------- 批量删除 ---------------------------------

  const selectedRowKeyList = ref([]);
  const hasSelected = computed(() => selectedRowKeyList.value.length > 0);

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  // 批量移除
  function batchDelete() {
    if (!hasSelected.value) {
      message.warning('请选择要删除的角色成员');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定移除这些角色成员吗？',
      okText: '确定',
      okType: 'danger',
      async onOk() {
        SmartLoading.show();
        try {
          let params = {
            authList: selectedRowKeyList.value,
            dsId: selectDataScopeId.value,
            isRelate: false,
          };
          let res=await dsApi.relateOrCancelQuarterAuth(params);
          if(res.success){
            message.success(res.message);
            selectedRowKeyList.value = [];
            await queryRoleEmployee();
          }
          else
            message.error(res.message);
        } catch (e) {
          smartSentry.captureError(e);
        } finally {
          SmartLoading.hide();
        }
      },
      cancelText: '取消',
      onCancel() {},
    });
  }
</script>

<style scoped lang="less">
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20px 0;
  }
  .button-style {
    margin: 0 10px;
  }
</style>
